package com.eds.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.eds.exception.BusException;
import com.eds.pojo.BaseResult;
import com.eds.pojo.CodeEnum;
import com.eds.service.OssImageService;
import com.eds.utils.FileUploadUtil;
import com.pojo.OssImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/fileManager")
public class UploadController {
    @Autowired
    private OssImageService ossImageService;

    //上传文件到Oss服务
    @PostMapping("/uploadImage")
    public BaseResult upload(MultipartFile file) throws IOException {
        //获取文件后缀名
        String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //通过uuid生成随机字符串当作文件名，防止同名覆盖
        String fileName = UUID.randomUUID().toString();
        fileName = fileName + substring;
        //把文件存至OOS服务
        String url = FileUploadUtil.uploadFile(fileName, file.getInputStream());
        if (url == null) {
            throw new BusException(CodeEnum.UPLOAD_IMAGES_ERROR.getCode(), CodeEnum.UPLOAD_IMAGES_ERROR.getMessage());
        }
        return BaseResult.ok("上传成功！", url);

    }

    //删除文件
    @DeleteMapping("/delete")
    public BaseResult delete(String filePath) throws IOException {
        //2. 上传图片到阿里云的OSS服务
        //提供阿里云oss服务的参数
        String endPoint = "https://oss-cn-beijing.aliyuncs.com";
        String ACCESS_KEY_ID = "LTAI5tKUpzZpCRgkmxRg4jZB";
        String ACCESS_KEY_SECRET = "XwqvwhN5MIZ4svNSQyTHtzk8KHK4Cy";
        String bucketName = "aaan";// 填写Bucket名称，在阿里云OSS中为存储数据而创建的空间的名称。
        //创建oss的客户端对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        //完成文件的删除
        ossClient.deleteObject(bucketName, filePath);
        //3. 响应结果
        return BaseResult.ok();
    }

    //获取默认地址
    @GetMapping("/getDefaultImage")
    public OssImage getDefaultImage() {
        OssImage defaultImage = ossImageService.getDefaultImage();
        return defaultImage;
    }

}
